﻿//
// 陈日红@2017/02/07 09:02
//
// 功能模块 服务接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AcexeService.Models;
using ServiceStack;
using ServiceStack.OrmLite;
using AcexeService.ServiceModel.Sys;


namespace AcexeService.ServiceInterface
{
    [Authenticate]
    public class FunctionService : Service
    {
        /// <summary>
        /// 取单个实体
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(GetFunction request)
        {
            string id = request.FuncId;
            var list = Db.Select<SYS_FUNCTION>(c => c.FUNCID == id);
            if (list.Count > 0)
            {
                return list[0];
            }
            return null;
        }

        /// <summary>
        /// 列表（分页、导出）
        /// </summary>
        /// <param name="requst"></param>
        /// <returns></returns>
        public object Any(GetFunctionList request)
        {
            var miniuigridmodel = new MiniUiGridModel<SYS_FUNCTION>();
            var model = request.SysFuncModel;

            var q = Db.From<SYS_FUNCTION>();

            if (!string.IsNullOrEmpty(request.FuzzyFuncName))
            {
                q.And(p => p.FUNCNAME.Contains(request.FuzzyFuncName));
            }

            q.And(x => x.ISDELETED == model.ISDELETED);

            if (!string.IsNullOrEmpty(model.FUNCNAME))
                q.And(x => x.FUNCNAME.Contains(model.FUNCNAME));

            if (!string.IsNullOrEmpty(model.FUNCDISPLAYNAME))
                q.And(x => x.FUNCDISPLAYNAME.Contains(model.FUNCDISPLAYNAME));

            if (!string.IsNullOrEmpty(model.FUNCURL))
                q.And(x => x.FUNCURL.Contains(model.FUNCURL));


            if (!string.IsNullOrEmpty(request.Page.SortField))
            {
                if (request.Page.SortOrder == "asc")
                    q.OrderByFields(request.Page.SortField);
                else
                    q.OrderByFieldsDescending(request.Page.SortField);
            }
            else
            {
                q.OrderBy(x => x.FUNCNAME);
            }

            var list = Db.Select<SYS_FUNCTION>(q);
            var resultlist = request.Page.IsGetWholeData ? list : list.Skip(request.Page.PageIndex * request.Page.PageSize).Take(request.Page.PageSize).ToList();

            miniuigridmodel.data = resultlist;
            miniuigridmodel.total = list.Count;

            return miniuigridmodel;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="requst"></param>
        /// <returns></returns>
        public object Any(AddFunction request)
        {
            var dto = new MessageDto();
            var model = request.SysFuncModel;

            if (string.IsNullOrEmpty(model.FUNCID))
            {
                dto.Flag = false;
                dto.Msg = "功能ID不允许为空";
                return dto;
            }
            if (string.IsNullOrEmpty(model.FUNCNAME))
            {
                dto.Flag = false;
                dto.Msg = "功能名称不允许为空";
                return dto;
            }
            if (string.IsNullOrEmpty(model.FUNCURL))
            {
                dto.Flag = false;
                dto.Msg = "功能程序路径不允许为空";
                return dto;
            }

            try
            {
                Db.Insert<SYS_FUNCTION>(model);
                dto.Flag = true;
                dto.Msg = "新增成功";
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
            }
            return dto;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(EditFunction request)
        {
            var dto = new MessageDto();
            var model = request.SysFuncModel;

            if (string.IsNullOrEmpty(model.FUNCID))
            {
                dto.Flag = false;
                dto.Msg = "功能ID不允许为空";
                return dto;
            }
            if (string.IsNullOrEmpty(model.FUNCNAME))
            {
                dto.Flag = false;
                dto.Msg = "功能名称不允许为空";
                return dto;
            }
            if (string.IsNullOrEmpty(model.FUNCURL))
            {
                dto.Flag = false;
                dto.Msg = "功能程序路径不允许为空";
                return dto;
            }

            try
            {
                var list = Db.Select<SYS_FUNCTION>(c => c.FUNCID == model.FUNCID);
                if (list.Count == 0)
                {
                    dto.Flag = false;
                    dto.Msg = "您编辑的功能不存在，请刷新页面后重试";
                    return dto;
                }

                var editmodel = list[0];
                editmodel = AcexeService.ServiceInterface.Lib.AutoTransfer.GetModel<SYS_FUNCTION>(editmodel, model);
                Db.Update<SYS_FUNCTION>(editmodel);
                dto.Flag = true;
                dto.Msg = "修改成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
            }
            return dto;
        }

        /// <summary>
        /// 删除(单个)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(DeleteFunction request)
        {
            var dto = new MessageDto();

            if (string.IsNullOrEmpty(request.FuncId))
            {
                dto.Flag = false;
                dto.Msg = "参数功能id为空";
                return dto;
            }
            try
            {
                //只作虚删除
                Db.ExecuteSql("UPDATE SYS_FUNCTION SET ISDELETED = @isdeleted WHERE FUNCID = @funcid", new { isdeleted = 1, funcid = request.FuncId });
                dto.Flag = true;
                dto.Msg = "作废成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
                return dto;
            }
        }

        /// <summary>
        /// 删除(批量)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(DeleteFunctions request)
        {
            var dto = new MessageDto();

            if (request.ListFuncId.Count == 0)
            {
                dto.Flag = false;
                dto.Msg = "参数功能id为空";
                return dto;
            }
            try
            {
                //只作虚删除
                var funcids = request.ListFuncId.ToSqlString();
                Db.ExecuteSql("UPDATE SYS_FUNCTION SET ISDELETED = @isdeleted WHERE FUNCID IN(" + funcids + ")", new { isdeleted = 1 });
                dto.Flag = true;
                dto.Msg = "作废成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
                return dto;
            }
        }

        public object Any(DeployFunction request)
        {
            var dto = new MessageDto();

            if (string.IsNullOrEmpty(request.FuncId))
            {
                dto.Flag = false;
                dto.Msg = "参数功能id为空";
                return dto;
            }

            if (string.IsNullOrEmpty(request.SysMenuModel.MENUPARENTID))
            {
                dto.Flag = false;
                dto.Msg = "上级菜单ID为空";
                return dto;
            }

            try
            {
                string parentid = request.SysMenuModel.MENUPARENTID;
                string moduleid = Db.Scalar<string>(Db.From<SYS_MODULE_MENU>().Where(x => x.MENUID == parentid).Select(x => x.MODULEID));

                // 找不到 module id
                if (string.IsNullOrEmpty(moduleid))
                {
                    dto.Flag = false;
                    dto.Msg = "您所选择的上级目录没有对应的模块";
                    return dto;
                }

                // 查找该级别下最大的排序号
                int maxorder = Db.Scalar<SYS_MENU, int>(x => Sql.Max(x.MENUORDERNUM), x => x.MENUPARENTID == parentid);
                request.SysMenuModel.MENUORDERNUM = maxorder + 1;


                using (System.Data.IDbTransaction dbTrans = Db.OpenTransaction())
                {
                    Db.Insert<SYS_MODULE_MENU>(new SYS_MODULE_MENU
                    {
                        MENUID = request.SysMenuModel.MENUID,
                        MODULEID = moduleid.ToString()
                    });

                    Db.Insert<SYS_MENU>(request.SysMenuModel);

                    dbTrans.Commit();
                }

                dto.Flag = true;
                dto.Msg = "发布成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
                return dto;
            }
        }
    }
}
